<?php

namespace app\api\controller;

use app\api\model\ExamLog;
use app\api\model\Training as TrainingModel;
use app\api\model\UserScoreLog;
use app\api\model\UserSign;
use app\common\controller\Api;
use think\Config;
use app\api\model\Third;
use app\api\model\User as UserModel;
use app\api\model\Category;


/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'GetPhone'];
    protected $noNeedRight = '*';
    public function login()
    {
        $code= $this->request->param('code');
        $appid = Config::get("site.appid");//小程序的appid
        $appSecret = Config::get("site.secret");// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        if(empty($wxResult)){
            $this->error('错误');
        }else{
            if(!empty($wxResult['errcode'])){
                $this->error($wxResult['errmsg']);
            }
            $openid = $wxResult['openid'];
            $where_third['openid']=$openid;
            $Third = new Third();
            $UserModel = new UserModel();
            $Third_find= $Third->get($where_third);
            if(empty($Third_find)){
                $data_user['nickname']=Config::get("site.nickname");
                $data_user['avatar']=Config::get("site.avatar");
                $data_user['jointime']=time();
                $data_user['status']="normal";
                $UserModel->save($data_user);
                $Third->user_id=$UserModel->id;
                $Third->platform="微信";
                $Third->apptype="小程序";
                $Third->openid=$openid;
                $Third->save();
                $this->auth->direct($UserModel->id);
                $data['is_mobile']=0;
            }else{
                $this->auth->direct($Third_find['user_id']);
                $user_find=$UserModel->get($Third_find['user_id']);
                if(empty($user_find['mobile'])){
                    $is_mobile=0;
                }else{
                    $is_mobile=1;
                }
                $data['is_mobile']=$is_mobile;
            }
            $data['token']=$this->auth->getToken();
            $this->success('',$data);
        }
    }
    public function GetPhone()
    {
        $user= $this->auth;
        $UserModel = new UserModel();
        $code= $this->request->param('code');
        $appid = Config::get("site.appid");//小程序的appid
        $appSecret = Config::get("site.secret");// 小程序的$appSecret
        $wxUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
        $result = self::curl_get($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);
        $GetPhoneUrl="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=".$wxResult['access_token'];

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $GetPhoneUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS =>'{"code": "'.$code.'"}',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);

        $wxResultse = json_decode($response, true);
        if(empty($wxResultse)){
            $this->error('错误');
        }else{
            if($wxResultse['errcode']!=0){
                $this->error('获取失败,请重试');
            }else{
                $where['id']=$user->id;
                $updata['mobile']=$wxResultse['phone_info']['phoneNumber'];

                //开始给身份id
                $Category = new Category();
                $datase['mobilePhone']=$wxResultse['phone_info']['phoneNumber'];
                $url="/nsj9201/worker/queryWorker";
                $urlse=$this->Monitor_url($url);
                $data=json_encode($datase, JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
                $response=$this->curl_data($urlse,$data);
                if(!empty($response['resultData']['isManager'])){
//                    dump($response['resultData']['isManager']);die;
                    if($response['resultData']['isManager']==true){
                        $updata['is_manage']=1;
                    }else{
                        $updata['is_manage']=0;
                    }
                    $workType=$response['resultData']['workType'];
                    $c_find=$Category->where(['name'=>$workType])->find();
                    if(empty($c_find)){
                        if($updata['is_manage']==1){
                            $type="manage";
                        }else{
                            $type="worker";
                        }
                        $add_data['type']=$type;
                        $add_data['name']=$workType;
                        $add_data['nickname']=$workType;
                        $add_data['createtime']=time();
                        $add_data['updatetime']=time();
                        $add_data['status']="normal";
                        $Category_id=$Category->save($add_data);
                        $updata['identity']=$Category_id->id;
                    }else{
                        $updata['identity']=$c_find['id'];
                    }

                }else{
                    $this->auth->logout();
                    $this->error('暂无权限');
                }


//                dump($updata);die;
                $UserModel->save($updata,$where);
                $this->success('');
            }
        }

    }
    public function info()
    {
        $UserSign = new UserSign();
        $Category = new Category();
        $user= $this->auth;
        $data['nickname']=$user->nickname;
        $data['avatar']=$user->avatar;
        $data['mobile']=$user->mobile;
        $data['score']=$user->score;
        $data['is_manage']=$user->is_manage;
        $data['identity_id']=$user->identity;
        $data['identity']=$Category->where(['id'=>$user->identity])->value('name');

        $where_sign['user_id']=$user->id;
        $where_sign['createtime']=['>',strtotime(date('Y-m-d 00:00:00',time()))];
        $is_sign_find=$UserSign->where($where_sign)->find();
        if(empty($is_sign_find)){
            $is_sign=0;
        }else{
            $is_sign=1;
        }
        $data['is_sign']=$is_sign;
        $data['day_score']=$this->this_day_score($user->id);
        $data['is_WriteOff']=$user->is_WriteOff;
        $data['all_score']=$user->all_score;
        $this->success('',$data);
    }
    public function edit()
    {
        $user= $this->auth;
        $param = $this->request->param();
        $UserModel= new UserModel();
        $where['id']=$user->id;
        $UserModel->save($param,$where);
        $this->success('');
    }
    public function sign()
    {
        $user= $this->auth;
        $UserSign = new UserSign();
        $where['user_id']=$user->id;
        $where['createtime']=['>',strtotime(date('Y-m-d 00:00:00',time()))];
        $is_find=$UserSign->where($where)->find();
        if(empty($is_find)){
            $data['user_id']=$user->id;
            $data['createtime']=time();
            $data['points']=Config::get("site.sign");
            $UserSign->save($data);
            //给积分了开始
            $score=$this->score_change($user->id,Config::get("site.sign"),'1',"签到获得积分",1);
            $this->score_day_log($user->id,$score,0,1);
        }else{
            $this->error('请勿重复签到');
        }
        $this->success('签到成功');
    }
    public function scoreLog()
    {
        $param = $this->request->param();
        $user= $this->auth;
        $UserScoreLog = new UserScoreLog();
        $where['user_id']=$user->id;
        if($param['type']==1){
            $where['score']=['>',0];
        }
        if($param['type']==2){
            $where['score']=['<',0];
        }
        if(!empty($param['start_time'])){
            $where['createtime']=['between',[strtotime($param['start_time']),strtotime($param['end_time'])]];
        }
        $list=$UserScoreLog->where($where)->order('id desc')->paginate(10);
        $this->success('',$list);
    }
    public function MissExam()
    {
        $start_time = $this->request->param('start_time',date('Y-m-1'));
        $end_time = $this->request->param('end_time',date('Y-m-d',time()));
        $user= $this->auth;
        $ExamLog = new ExamLog();
        $diffInSeconds=strtotime($end_time)-strtotime($start_time);
        $days = floor($diffInSeconds / (60 * 60 * 24))+1;
        if($days>90){
            $this->error('最多只能查询90天');
        }
        for ($i=0;$i<$days;$i++){
            $date[]=date('Y-m-d',strtotime($start_time)+86400*$i);
        }
        $datese=[];
        foreach ($date as $k=>$v){
            $where['user_id']=$user->id;
            $where['createtime']=['between',[strtotime($v.' 00:00:00'),strtotime($v.' 23:59:59')]];
            $where['status']=1;
            $find=$ExamLog->where($where)->find();
            $datese[$k]['date']=$v;
            $miss_exam=1;
            if(!empty($find)){
                $miss_exam=0;
            }
            $datese[$k]['miss_exam']=$miss_exam;
        }
        $data['month']=self::MissExamCount($user->id,date('Y-m-1'),date('Y-m-d',time()));
        $data['all_num']=self::MissExamCount($user->id,date('Y-m-d',$user->jointime),date('Y-m-d',time()));
        $data['date']=$datese;
        $this->success('',$data);
    }
    public function MissExamCount($user_id,$start_time,$end_time)
    {
        $ExamLog = new ExamLog();
        $diffInSeconds=strtotime($end_time)-strtotime($start_time);
        $days = floor($diffInSeconds / (60 * 60 * 24))+1;

        $where['user_id']=$user_id;
        $where['createtime']=['between',[strtotime($start_time),strtotime($end_time)]];
        $where['status']=1;
        $count=$ExamLog->where($where)->count();

        return $days-$count;
    }

    public function studyLog()
    {
        $user= $this->auth;
        $TrainingModel = new TrainingModel();
        $where['user_id']=$user->id;
        $where['type']=4;
        $list=db('score_day_log')->where($where)->order('id desc')->paginate(10)->each(function ($item)use($TrainingModel){
            $Training_find=$TrainingModel->where(['id'=>$item['external_id']])->find();
            $item['title']=$Training_find['title'];
            $item['cover_image']=$Training_find['cover_image'];
            return $item;
        });
        $this->success('',$list);
    }


    /**
     * curl
     * @param $url
     * @param $httpCode
     * @return bool|string
     */
    public function curl_get($url, &$httpCode = 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //不做证书校验,部署在linux环境下请改为true
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        $file_contents = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $file_contents;
    }
}
